<?php
namespace app\mobile\model;

use think\Model;
use think\Request;

/**
 * Class Image
 * @package app\mobile\model  图片上传类
 */
class Image extends Model
{
    /*
     * 多图上传
     */
    public function img_upload($name,$path)
    {
        
        $files = Request::instance()->file($name);
        if (!empty($files)){
            $opt = [];
            foreach ($files as $_file){
                $info = $_file->move(ROOT_PATH . 'public' .  DS . 'appWeb' . DS. $path);
                $opt[] = self::thumb('appWeb'. DS . $path . DS . date('Ymd'),$info->getFilename());
            }
            return implode('|',$opt);
        }
    }
    /*
     * 单图上传
     */
    public function one_img_upload($name,$path)
    {
        $file = Request::instance()->file($name);
        if (!empty($file)){
            $info = $file->move(ROOT_PATH . 'public' .  DS . 'appWeb' . DS. $path);
            $square = 0;
            if ($path == 'avatar'){  //头像上传
                $square = 1;
            }
            $upload_path = self::thumb('appWeb'. DS . $path . DS . date('Ymd'),$info->getFilename(),$square);
            return $upload_path;
        }
        return '';
    }
    /*
     * 压缩图片
     * $square  是否开始正方形 0否 1是
     */
    public function thumb($path,$name,$square = 0)
    {
        //获取图片尺寸
        $image = filesize(ROOT_PATH . 'public' . DS . $path . DS . $name);
        if ($image > 102400){
            $image_info = \think\Image::open(ROOT_PATH . 'public' . DS . $path . DS . $name);
            $width = $image_info->width();
            $height = $image_info->height();
            $size = $width;
            if ($width > $height){
                $size = $height;
            }
            //缩略图名称
            if (strstr($name,'_thumb')){
                @unlink(ROOT_PATH . 'public' . DS . $path . DS . $name);
                $thumb_file_name = $name;
            }else{
                $thumb_name = explode('.',$name);
                $ext = array_pop($thumb_name);
                $thumb_file_name = implode('',$thumb_name)."_thumb".'.'.$ext;
            }
            $thumb_name = ROOT_PATH . 'public' . DS . $path . DS .$thumb_file_name;
            if ($square){
                $image_info->thumb($width*0.8,$height*0.8,\think\Image::THUMB_CENTER)->save($thumb_name);
            }else{
                $image_info->thumb($size*0.8,$size*0.8,\think\Image::THUMB_CENTER)->save($thumb_name);
            }
            chmod($thumb_name,0777);
            unset($image_info,$image);
            self::thumb($path,$thumb_file_name);
            return $path . DS . $thumb_file_name;
        }
        unset($image);
        return $path . DS . $name;
    }
}